package com.lx.controller;

import com.lx.dao.UserDao;
import com.lx.entity.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户操作
 *
 * @author 段誉
 * @create 2019-04-11 9:52
 */
@RestController
public class UserController {
  @Autowired
  private UserDao userDao;

  @PostMapping("user")
  public String userAdd(User user) {
    return userDao.userInsert(user) != 0 ? "success" : "fail";
  }

  /**
   * @desc 测试CachePut注解
   * 缓存名字为"User","userId"作为key
   * @Author 段誉
   * @Date 2019/4/11 9:56
   * @method
   */
  @Cacheable(cacheNames = "User", key = "#userId")
  @GetMapping("/testCacheable/{userId}")
  public User testCacheable(@PathVariable("userId") Integer userId) {
    return userDao.userQuery(userId);
  }

  /**
   * @desc 缓存名字为"User","userId"作为key
   * @Author 段誉
   * @Date 2019/4/11 9:56
   * @method
   */
  @CachePut(cacheNames = "User", key = "#userId")
  @GetMapping("/testCachePut/{userId}")
  public User testCachePut(@PathVariable("userId") Integer userId) {
    return userDao.userQuery(userId);
  }

  /**
   * @desc 测试CacheEvict注解清空指定用户缓存
   * @Author 段誉
   * @Date 2019/4/11 9:56
   * @method
   */
  @CacheEvict(cacheNames = "User", key = "#userId")
  @GetMapping("/testCacheEvict/{userId}")
  public String testCacheEvict(@PathVariable("userId") Integer userId) {
    return "cache for " + userId + " has been flushed";
  }

  /**
   * @desc 测试CacheEvict注解的allEntries属性清空所有用户缓存
   * @Author 段誉
   * @Date 2019/4/11 9:56
   * @method
   */
  @CacheEvict(cacheNames = "User", allEntries = true)
  @GetMapping("/testAllEntries")
  public String testAllEntries() {
    return "All caches have been flushed";
  }
}
